import 'dart:typed_data';
import 'dart:ui';
import 'package:app/components/TimeView.dart';
import 'package:app/model/app_config.dart';
import 'package:app/model/model.dart';
import 'package:app/page/add.dart';
import 'package:app/router/router.dart';
import 'package:app/utils/utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver_plus/image_gallery_saver_plus.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

class CountdownView extends StatefulWidget with RouterBridge<ChildrenEvent> {
  const CountdownView({super.key});
  @override
  State<CountdownView> createState() => _CountdownViewState();
}

class _CountdownViewState extends State<CountdownView> {
  var isInitialized = false;
  late ChildrenEvent childrenEvent;
  final _boundaryKey = GlobalKey();
  void _showMessage(String content) {
    Fluttertoast.showToast(msg: content);
  }

  void _saveImageTOAlbum(BuildContext context) async {
    var storagePermission = await Utils.getPhotoPermission();
    if (!storagePermission) {
      _showMessage("权限被拒绝");
      return;
    }

    final boundary = _boundaryKey.currentContext?.findRenderObject();
    if (boundary != null && boundary is RenderRepaintBoundary) {
      final image = await boundary.toImage(pixelRatio: 7.0);
      ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
      if (byteData != null) {
        final result = await ImageGallerySaverPlus.saveImage(
          byteData.buffer.asUint8List(),
          name: childrenEvent.name.value,
        );
        if (result != null && mounted) {
          TDToast.showSuccess(
            '图片保存成功',
            direction: IconTextDirection.vertical,
            context: context,
          );
        }
      }
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (!isInitialized) {
      final args = widget.argumentsOf(context);
      if (args != null) {
        childrenEvent = args;
        isInitialized = true;
        return;
      }
      _showMessage("参数错误，请返回上一页重试");
      Navigator.maybePop(context);
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TDNavBar(
        height: 48,
        titleWidget: Obx(
          () => Text(
            childrenEvent.name.value,
            style: TextStyle(color: Colors.white),
          ),
        ),
        centerTitle: false,
        backgroundColor: StaticAppConfig.appBarColor,
        titleFontWeight: FontWeight.w600,
        useDefaultBack: false,
        screenAdaptation: true,
        leftBarItems: [
          TDNavBarItem(
            icon: Icons.chevron_left,
            iconColor: Colors.white,
            action: () {
              Navigator.maybePop(context);
            },
          ),
        ],
        rightBarItems: [
          TDNavBarItem(
            icon: TDIcons.image_add,
            iconColor: Colors.white,
            action: () {
              _saveImageTOAlbum(context);
            },
          ),
          TDNavBarItem(
            icon: TDIcons.pen_brush,
            iconColor: Colors.white,
            action: () {
              context.routeOf<Add>().arguments(childrenEvent).to();
            },
          ),
        ],
      ),
      body: Container(
        decoration: BoxDecoration(color: Color(0xFFCCCCCC)),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(height: 120),
              RepaintBoundary(
                key: _boundaryKey,
                child: TimeView(childrenEvent: childrenEvent, isMin: false),
              ),
              if (childrenEvent.imgUrl.isNotEmpty)
                Expanded(
                  child: Align(
                    alignment: Alignment.bottomRight,
                    child: Padding(
                      padding: EdgeInsets.only(bottom: 150, right: 30),
                      child: TDFab(
                        theme: TDFabTheme.primary,
                        icon: Icon(TDIcons.delete),
                        onClick: () async {
                          var args = CountdownEventClassList.create();
                          Utils.delteCacheImage(
                            args.countdownEventList,
                            childrenEvent.imgUrl.value,
                            childrenEvent.childrenId.value,
                          ).then((_) {
                            var ar = args
                                .findCountdownEventClassById(
                                  childrenEvent.parentId.value,
                                )
                                ?.findEventChildById(
                                  childrenEvent.childrenId.value,
                                );
                            if (ar != null) {
                              ar.updateChildrenEvent(
                                imgUrl: '',
                                blurRadius: 0.0,
                                textColor: Colors.black,
                              );
                              setState(() {
                                childrenEvent.updateChildrenEvent(
                                  imgUrl: '',
                                  blurRadius: 0.0,
                                  textColor: Colors.black,
                                );
                              });
                            }
                          });
                        },
                      ),
                    ),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }
}
